Page({
  data: {
    tabs: [{
      status: '',
      name: '全部',
      pageIndex: 1,
      noMore: false
    }, {
      status: 0,
      name: '待付款',
      pageIndex: 1,
      noMore: false
    }, {
      status: 1,
      name: '待发货',
      pageIndex: 1,
      noMore: false
    }, {
      status: 2,
      name: '待收货',
      pageIndex: 1,
      noMore: false
    }, {
      status: 4,
      name: '已完成',
      pageIndex: 1,
      noMore: false
    }],
    tabIndex: 0,
    orderList: [],
    loading: false,
    scrollTop: 0
  },
  onLoad: function(options) {
    this.setData({
      tabIndex: options.tab || 0,
      statusCode: require('../../config/statusCode').order
    });
  },
  onShow: async function () {
    this.setData({
      isLogined: await wx.user.hasLogin()
    }, () => {
      this.getMyOrder();
    });
  },
  onPullDownRefresh: function () {
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 300);
  },
  onReachBottom: function () {
    this.setData({
      loading: true
    });
    this.getMyOrder();
    this.setData({
      loading: false
    });
  },
  onPageScroll: function (e) {
    this.setData({
      scrollTop: e.scrollTop
    });
  },
  getMyOrder: function () {
    let tabIdx = this.data.tabIndex,
        curTab = this.data.tabs[tabIdx],
        orderList = this.data.orderList[tabIdx] || [];
    if ((orderList.length && !this.data.loading) || curTab.noMore) return;
    wx.util.request(this, {
      body: {
        page: curTab.pageIndex,
        synthesize_status: curTab.status
      }
    }, '', this.data.loading).then(res => {
      for (let item of res) {
        item.product_money = wx.util.formatAmount(item.product_money);
      }
      res.forEach((order) => {orderList.push(order)});
      this.setData({
        [`orderList[${tabIdx}]`]: orderList,
        [`tabs[${tabIdx}].noMore`]: res.length < 10,
        [`tabs[${tabIdx}].pageIndex`]: curTab.pageIndex + 1
      });
    }).catch(err => {
      console.log(err);
    });
  },
  change: function (e) {
    this.setData({
      tabIndex: e.detail.index
    }, () => {
      this.getMyOrder();
    });
  },
  delete: function (e) {
    this.setData({
      modal: true,
      modalClick: 'delOrder',
      modalContent: '删除后不可撤销',
      orderListIdx: e.currentTarget.dataset.index
    });
  },
  delOrder: function (e) {
    this.hideModal();
    if (e.detail.index != 1) return;
    let idx = this.data.orderListIdx,
        tab = this.data.tabIndex,
        list = this.data.orderList[tab];
    wx.util.request('order.del', {
      query: `id=${list[idx].id}`
    }).then(res => {
      list.splice(idx, 1)
      this.setData({
        [`orderList[${tab}]`]: list
      });
    }).catch(err => {
      console.log(err);
    });
  },
  hideModal: function () {
    this.setData({
      modal: false
    });
  },
  detail: function (e) {
    wx.navigateTo({
      url: `detail?id=${e.currentTarget.dataset.id}`
    });
  },
  // 倒计时结束
  end: function (e) {
    console.log(e)
  },
  payment: function (e) {
    wx.navigateTo({
      url: `../payment/index?id=${e.currentTarget.dataset.id}`,
    });
  },
  refund: function (e) {
    wx.navigateTo({
      url: `../refund/apply?id=${e.currentTarget.dataset.id}`,
    });
  },
  delivered: function (e) {
    this.setData({
      modal: true,
      modalClick: 'takeDelivery',
      modalContent: '请确认已收到货物，否则有可能财物两空',
      takeDeliveryId: e.currentTarget.dataset.id
    });
  },
  takeDelivery: function (e) {
    this.hideModal();
    if (e.detail.key === 'cancel') return;
    wx.util.request('order.delivery', {
      query: `id=${this.data.takeDeliveryId}`
    }).then(() => {
      this.updateList(this.data.takeDeliveryId, 4);
    });
  },
  // 订单取消支付
  close: function (e) {
    let id = e.currentTarget.dataset.id;
    wx.util.request('order.cancel', {
      query: `id=${id}`
    }).then(() => {
      this.updateList(id, -4);
    });
  },
  evaluate: function (e) {
    wx.navigateTo({
      url: `../evaluate/product?id=${e.currentTarget.dataset.id}&evaluate=${e.currentTarget.dataset.value}`,
    });
  },
  updateList: function(orderId, status) {
    // 别以为什么都值得“优雅”，最好用的处理方法是最笨的，比如以下(手动滑稽)
    let list = this.data.orderList;
    for (let i in list) {
      for (let j in list[i]) {
        let order = list[i][j];
        if (order.id == orderId) {
          if (this.data.curTab == 0 && this.data.curTab == i) {
            // 更新状态
            order.order_status = status;
          } else {
            // 移出列表
            list[i].splice(j, 1);
          }
          break;
        }
      }
    }
    this.setData({
      orderList: list
    });
  }
})